package com.example.demo.common.persistence.util;/**
 * Created by kete on 2017-10-19.
 */





import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：kete
 * 创建时间：2017-10-19 14:49
 * 功能描述：
 * 版本：
 */
public class JsonUtil {
    private final static ObjectMapper objectMapper;
    private final static ObjectMapper objectMapperNotNull;

    static{
        objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);

        objectMapperNotNull = new ObjectMapper();
        objectMapperNotNull.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapperNotNull.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);

    }

    public static <T> T toBean(String content, Class<T> valueType) {

        try {
            return objectMapper.readValue(content, valueType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> T toBean(String content, TypeReference valueTypeRef) {

        try {
            return objectMapper.readValue(content, valueTypeRef);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static <T> List<T> toList(String content, Class<T> valueType) {

        try {
            JsonParser parser = objectMapper.getJsonFactory().createJsonParser(content);

            JsonNode nodes = parser.readValueAsTree();
            List<T> list  = new ArrayList<T>(nodes.size());
            for(JsonNode node : nodes){
                list.add(objectMapper.readValue(node.asText(), valueType));
            }

            return list;
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String toJSon(Object object) {

        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    public static String toJSonNotNull(Object object) {

        try {
            return objectMapperNotNull.writeValueAsString(object);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
